<template>
    <div>
        <rui-page :defines="defines">
            <financial-prod
                :isShowDetails="isShowDetails"
                ref="financialProd"
                :saveStatus="saveStatus"
                :uuid="uuid"
                :intropath="intropath"
                :curTab="curTab"
                :applyNo="applyNo"
                :proessForm="proessForm"
                :additionalProessForm="additionalProessForm"
                :carProessForm="carProessForm"
                :remarkForm="remarkForm"
                @caluMaxValue="caluMaxValue"
                @passValiate="passValiate"
                @queryProId="queryProId"
                @isShowModel="isShowModel"
                :queryFormEl="queryFormEl"
                @valiateProRes="valiateProRes"
                :productId="productIdSelect"
                :productName="productNameSelect"
            >
                <template slot="afsProduct">
                    <div>
                        <Modal width="50%" v-model="proessModel" :footer-hide="true" @on-cancel="cancelModel">
                            <div class="scheduleTitle">
                                 <span v-for="(item,index) in scheduleTitleList" @click="tagTitle(item.value)"
                                       :class="{curScheStyle:curSchedule===item.value}">
                                     {{item.title}}
                                 </span>
                            </div>
                            <div class="sliderList">
                                <div>
                                    <Form ref="proessForm" :model="proessForm" :rules="proessFormValidate" :label-width="140">
                                        <Row v-for="(item,index) in proessForm.proessList" :key="index" style="padding: 0px 30px;">
                                            <Col :span="2">
                                                <div style="padding-top: 8px;">
                                                    {{item.no}}<span>期</span>
                                                </div>
                                            </Col>
                                            <Col :span="5">
                                                <FormItem label="" :prop="'proessList['+index+'].inputValue'"
                                                          class="inline-block mb10" :label-width="0">
                                                    <Input v-model="item.inputValue" placeholder=""
                                                           @on-blur="getInputValue(item.inputValue,index,isreadonly)"
                                                    />
                                                </FormItem>
                                            </Col>
                                            <Col :span="16" offset="1">
                                                <Slider :value="item.proessValue" range :disabled="true"
                                                        :max="maxValue" :step="stepNumber"></Slider>
                                            </Col>
                                        </Row>
                                    </Form>
                                </div>
                            </div>
                            <div style="text-align: center;margin:0px;" class="submit">
                                <Button type="primary" @click="calculateIntrate">计算</Button>
                            </div>
                        </Modal>
                    </div>
                </template>
                <template slot="afsProduct">
                    <Table border :columns="columns" :data="proessForm.proessList" ref="tableRepayPlan">
                        <template slot-scope="{ row, index }" slot="modifyAmount">
                            <InputNumber v-model="proessForm.proessList[index].modifyAmount" :min="-proessForm.proessList[index].yueGong" :disabled="isShowDetails"/>
                        </template>
                    </Table>
                    <Button type="primary" icon="md-download-outline" @click="exportData" >还款计划表下载</Button>
                    <br>
                    <Form ref="measureForm" :model="measureForm" :label-width="150">
                        <Row>
                            <Col span="12">
                                <FormItem label="测算系数" prop="measureCoefficient" :rules="{validator:isDicmalValiate,trigger: 'blur',required: true}">
                                    <InputNumber :max="2" :min="0" :step="0.1" v-model="measureForm.measureCoefficient" style="width: 250px" :disabled="isShowDetails" />
                                </FormItem>
                            </Col>
                            <Col span="12">
                                <FormItem label="IRR(%)" prop="measureIrr">
                                    <InputNumber :min='0' :max="100"
                                                 v-model="measureForm.measureIrr"
                                                 autocomplete="off" :disabled="readonly"
                                                 :formatter="value => `${value}%`"
                                                 :parser="value => value.replace('%', '')"
                                                 style="width:250px"
                                    />
                                    <Button type="primary" icon="md-calculator" @click="calculateIrr" v-if="!isShowDetails" :loading="submitLoading">测算</Button>
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                    <Alert>
                        <Row style="text-align: center;">
                            <div class="submit">
                                <Button type="primary" icon="md-calculator" @click="calculate" v-if="!isShowDetails" :loading="submitLoading">计算</Button>
                                <Button type="primary" icon="md-bookmark" @click="financialSave" v-if="!isShowDetails" :loading="submitLoading">保存</Button>
                                <Button type="primary" icon="md-backspace" @click="backPage" :loading="submitLoading" >关闭</Button>
                            </div>
                        </Row>
                    </Alert>
                </template>
            </financial-prod>
            <rui-table
                :defineId="'defineMeasure'"
                :fixedLeft="['action']"
                :showIndex="false"
                :select="false"
                :columns="measurenColumns"
                :slots="[{key:'action',slot:'action'}]"
                @loadDatas="queryData"
                ref-query="searchMeasureForm"
                ref="planmeasureTable"
                v-if="!isShowDetails"
            >
                <template slot="action" slot-scope="{ row }">
                    <div>
                        <Button type="primary" size="small" @click="showMeasure(row)">查看</Button>
                        <Button type="error" size="small" @click="delMeasure(row)">删除</Button>
                    </div>
                </template>
            </rui-table>

        </rui-page>
    </div>
</template>
<script>
    import FinancialProd from "@/components/financial-prod";
    import * as applyUtils from '_p/afs-apply/assets/js/utils.js';
    import * as utils from '_p/afs-apply/assets/js/utils.js';
    import measureDefine from "./measure-define";
    import {
        calculateIrr,
        getMeasureInfoList,
        getMeasureInfo,
        delMeasureInfo,
    } from "@/projects/afs-core-business/api/afs-product/product-measure/product-measure";
    import {
        saveCostList,
    } from "_p/afs-apply/api/apply-report/personal/financialProducts.js"
    export default {
        name:"demo",
        data(){
            let isDicmalValiate=(rule, value, callback)=> {
                if (value) {
                    if (!utils.keepTwoDicmal(value)) {
                        callback(new Error("最多为两位小数"))
                        return;
                    }
                }
                callback()
            }
            return {
                productIdSelect:this.afs.getPageParams(this).productIdSelect||'',
                productNameSelect:this.afs.getPageParams(this).productNameSelect||'',
                measureId:this.afs.getPageParams(this).measureId,
                applyNo:this.afs.getPageParams(this).measureId,
                submitLoading: false,
                isDicmalValiate:isDicmalValiate,
                saveStatus:{
                    disabled:true,
                },
                intropath:"afsProduct",
                curTab:0,
                uuid:"",
                isShowDetails:false,
                proessForm:{
                    proessList:[],
                },
                additionalProessForm:{
                    proessList:[],
                },
                carProessForm:{
                    proessList:[],
                },
                proessFormValidate:{},
                stepNumber:0.01,
                maxValue:800,
                saveStatus:{
                    disabled:true,
                },
                columns: [
                    {
                        title: '期数',
                        key: 'no'
                    },
                    {
                        title: '每月还款本金',
                        key: 'benJin'
                    },
                    {
                        title: '每月还款利息',
                        key: 'liXi'
                    },
                    {
                        title: '月供',
                        key: 'yueGong'
                    },
                    {
                        title: '剩余本金',
                        key: 'yuE'
                    },
                    {
                        title: '每月利息',
                        key: 'monthlyInterest'
                    },
                    {
                        title: '复合利息',
                        key: 'compoundInterest'
                    },
                    {
                        title: '修改金额',
                        key: 'modifyAmount',
                        slot: 'modifyAmount'
                    }
                ],
                measureForm:{
                    measureCoefficient:null,
                    measureIrr:null,
                },
                readonly:true,
                calculateLogo:true,
                measurenColumns : [
                    'productName','loanTerm','loanAmt','measureIrr','createTime','action'
                ],
                productId:"4442447642494411562",
                isMeasure:false,
                remarkForm: {
                    remark: "",
                },

                //弹窗开关
                proessModel:false,
                curSchedule: "00",
                scheduleTitleList: [],
                isreadonly: false,
            }
        },
        created(){
            this.uuid=this.getUuid();
            console.log("creatd："+this.afs.getPageParams(this));
            if(this.afs.getPageParams(this).measureId!=null){
                this.getMeasureInfo();
                this.isShowDetails = true;
            }
        },
        mounted(){
            this.curTab=2;
            console.log("mounted："+this.afs.getPageParams(this).productIdSelect,this.afs.getPageParams(this).productNameSelect);
        },
        components:{
            FinancialProd
        },
        methods:{
            backPage() {
                this.afs.closeTab(this);
            },
            getUuid () {
                let seed = 0;
                const now = Date.now();
                return 'ui-tab-' + now + '-' + (seed++);
            },
            getInputValue(value,index){
                if(applyUtils.isTwoDicmal(value)){
                    this.proessForm.proessList[index].proessValue=[0,""]
                    this.proessForm.proessList[index].proessValue.splice(1,1,value);
                }
            },
            passValiate(){
                this.initProessValiate();
            },
            // 校验附加贷
            initProessValiate(){
                for (let i = 0; i < this.proessForm.proessList.length; i++) {
                    this.proessFormValidate["proessList[" + i + "].inputValue"] = [
                        {validator:applyUtils.isTwoDicmalValiate,trigger:"blur"}
                    ];
                }
            },
            queryFormEl() {
                return this.$refs.proessForm;
            },
            caluMaxValue(maxValue){
                this.maxValue=maxValue;
            },
            queryProId(id){
                console.log(id,"id");
                this.productId = id;
                this.refresh();
                this.proessForm.proessList=[];
                this.measureForm.measureIrr = null;
            },
            //计算
            calculate(){
                this.$refs.financialProd.calculate();
            },
            //计算的校验
            valiateProRes(val){
                console.info("校验是否通过"+val)
                if(val){
                    this.calculateLogo = false;
                    this.isMeasure = false;//测算判断为否
                    this.measureForm.measureCoefficient = 1;
                }else{
                    this.calculateLogo = true;
                }
            },
            //测算
            calculateIrr(){
                if(this.calculateLogo){
                    this.$Message.error("请先计算还款计划表！");
                    return;
                }
                if(this.measureForm.measureCoefficient == null || this.measureForm.measureCoefficient == undefined){
                    this.$Message.error("请填写测算系数！");
                    return;
                }
                var listLength = this.proessForm.proessList.length;
                for(var i=0;i<listLength;i++){
                    if(this.proessForm.proessList[i].modifyAmount == null || this.proessForm.proessList[i].modifyAmount == undefined){
                        this.$Message.error("请填写修改金额！");
                        return;
                    }
                }
                this.$refs["measureForm"].validate((valid) => {
                    if (valid) {
                        let param = this.measureForm;
                        param.repaymentInfoList = this.proessForm.proessList;
                        param.totalLoanAmt =  this.$refs.financialProd.queryTotalLoanAmt();
                        console.info(JSON.stringify(param));
                        calculateIrr(param).then(res => {
                            if (res.code === "0000") {
                                this.$Message.success("测算成功！");
                                this.measureForm.measureIrr = res.data;
                                this.refresh();
                                this.isMeasure = true;//测算判断为是
                            }
                        });
                    }
                });
            },
            //保存
            financialSave(){
                if(this.isMeasure){
                    // let param=this.$refs.financialProd.querySaveData();
                    let param = JSON.parse((JSON.stringify(this.$refs.financialProd.querySaveData()) + JSON.stringify(this.measureForm)).replace(/}{/, ','));
                    console.info(JSON.stringify(param));
                    if(!param){
                        return false;
                    }
                    param.repaymentInfoList = this.proessForm.proessList;//整合还款计划

                    saveCostList(param).then(res=>{
                        if(res.code=="0000"){
                            this.refresh();
                            this.$Message.success("保存测算结果成功");
                            this.isMeasure = false;//测算判断为否
                        }
                    })
                }else{
                    this.$Message.warning("请先进行测算，再保存！");
                }
            },
            //查看测算结果
            showMeasure(row){
                this.afs.newTab(this,'projects/afs-core-business/pages/product/product-measure/productMeasure','IRR测算','ios-add',{measureId:row.id},row.id,[],true);
            },
            //测算结果初始化
            refresh() {
                this.$refs['planmeasureTable'].reloadData();
            },
            queryData(queryData) {
                queryData["productId"] = this.productId;
                getMeasureInfoList(queryData).then(res => {
                    if (res.code === "0000") {
                        let {records, total} = res.data;
                        this.$refs.planmeasureTable.updateTableData(records, total);
                    }
                });
            },
            //测算信息初始化，查看时专用
            getMeasureInfo() {
                getMeasureInfo({
                    id: this.measureId,
                }).then(res => {
                    if (res.code === "0000") {
                        let {productMeasureInfo, list} = res.data;
                        this.measureForm = productMeasureInfo;
                        this.proessForm.proessList = list;
                    }
                });
            },
            //关闭弹窗
            cancelModel() {
                this.proessModel = false;
            },
            tagTitle(value) {
                this.curSchedule = value;
            },
            //弹窗还款计划表计算
            calculateIntrate() {
                this.$refs.financialProd.calculateIntrate();
            },
            //展示弹窗
            isShowModel(val) {
                this.proessModel = val;
            },
            scheduleTitle(val) {
                this.scheduleTitleList = val;
            },
            //删除测算结果
            delMeasure(row){
                this.$Modal.confirm({
                    title: "确认删除",
                    content: "确认要删除此测算方案?",
                    onOk: () => {
                        delMeasureInfo({id: row.id,}).then(res => {
                            if (res.code === "0000") {
                                this.refresh();
                                this.$Message.success(res.msg);
                            }else{
                                this.$Message.error(res.msg);
                            }
                        });
                    }
                });
            },
            //还款计划表下载
            exportData (type) {
                this.$refs.tableRepayPlan.exportCsv({
                    filename: '还款计划表'
                });
            },
        },
        computed: {
            defines() {
                return [
                    {
                        id: "defineMeasure",
                        fields: measureDefine
                    }
                ];
            }
        },
    }
</script>
<style scoped>
    .common_content {
        background-color: white;
        padding: 16px;
    }
</style>
